#!/usr/bin/python
import os
import datetime
import time

from packet import packet_fun,unpacket_fun

def tlv_send(tmp_tag, tmp_len, tmp_val):
    tmp_tlv = []
    tmp_tlv_packet = []
  
    tmp_tlv.append(tmp_tag&0xFF)
    tmp_tlv.append((tmp_tag>>8)&0xFF)
    tmp_tlv.append((tmp_tag>>16)&0xFF)
    tmp_tlv.append((tmp_tag>>24)&0xFF)
    tmp_tlv.append(tmp_len&0xFF)
    tmp_tlv.append((tmp_len>>8)&0xFF)
    tmp_tlv_packet = tmp_tlv + tmp_val
    tlv_total_packet = packet_fun(tmp_tlv_packet, len(tmp_tlv_packet))
    #unpacket_fun(tlv_total_packet)
    return tlv_total_packet

def tlv_str_send(tmp_tlv_packet):
    tlv_packet_str = ""
    for index in range(len(tmp_tlv_packet)):
        tlv_packet_str += str(hex(tmp_tlv_packet[index]))
        #tlv_packet_str  += chr(tlv_packet[index])

    tlv_packet_str = tlv_packet_str.replace("0x","\\x")
    tlv_packet_str = tlv_packet_str.replace("L","")
    #print(tlv_packet_str)
    tmp_cmd = 'echo -ne \'' + tlv_packet_str + '\' > /dev/ttymxc2'
    
    return tmp_cmd

def lowlevel_rw_fun(tag, value):
    recv_packet = []
    if not os.path.exists("./tmp_data_dir"):
	os.makedirs("./tmp_data_dir")
   
    cmd = 'stty -F /dev/ttymxc2 speed 1000000 -echo raw >> ./tmp_data_dir/tmp_log.txt'
    os.system(cmd)
    #cmd = 'cat /dev/ttymxc2 > /dev/null &'
    #os.system(cmd)
    cmd = 'cat /dev/ttymxc2 > ./tmp_data_dir/tmp_uart_read &'
    os.system(cmd)
    tlv_packet = tlv_send(tag, len(value), value)
    cmd = tlv_str_send(tlv_packet) 
    os.system(cmd)
    time.sleep(0.5)
    cmd = 'killall -9 cat'
    os.system(cmd)
    recv_packet = []
    fd = open('./tmp_data_dir/tmp_uart_read', 'rb')
    for i in range (os.path.getsize('./tmp_data_dir/tmp_uart_read')):
    	data = fd.read(1)
        recv_packet.append(hex(ord(data)))
    fd.close()
    recv_packet = unpacket_fun(recv_packet)
    
    return recv_packet

'''
if __name__ == '__main__':

    if not os.path.exists("./tmp_data_dir"):
	os.makedirs("./tmp_data_dir")
   
   # cmd = 'stty -F /dev/ttymxc2 speed 1000000 cs8 -parenb -cstopb -echo igncr -icanon >> ./tmp_data_dir/tmp_log.txt'
    cmd = 'stty -F /dev/ttymxc2 speed 1000000 -echo raw >> ./tmp_data_dir/tmp_log.txt'
    os.system(cmd)
    tlv_packet = tlv_send(0x01010101, 3, [1,3,4])
    cmd = tlv_str_send(tlv_packet) 
    os.system(cmd)
    cmd = 'cat /dev/ttymxc2 > ./tmp_data_dir/tmp_uart_read &'
    os.system(cmd)
    time.sleep(0.5)
    cmd = 'killall -9 cat'
    os.system(cmd)

    recv_packet = []

    fd = open('./tmp_data_dir/tmp_uart_read', 'rb')
    for i in range (os.path.getsize('./tmp_data_dir/tmp_uart_read')):
    	data = fd.read(1)
        recv_packet.append(data)
    fd.close()
    #print(recv_packet)
    recv_packet = unpacket_fun(recv_packet)
    print(recv_packet)
'''



